#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This code runs a report and downloads it as a csv file."""

__author__ = 'gspillmann@google.com (Guillaume Spillmann)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
import time
import csv

# Import appropriate classes from the client library.
from adspygoogle.dfp import DfpUtils
from adspygoogle.dfp.DfpClient import DfpClient


# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# sandbox environment.
report_service = client.GetReportService(
    'https://www.google.com', 'v201206')


# Create report job.
report_job = {
    'reportQuery': {
        'dimensions': ['AD_UNIT', 'ADVERTISER', 'ORDER', 'LINE_ITEM', 'LINE_ITEM_TYPE', 'CREATIVE_SIZE'],
        'columns': ['TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', 'TOTAL_LINE_ITEM_LEVEL_CLICKS',
                    'TOTAL_LINE_ITEM_LEVEL_CTR'],
        'dateRangeType': 'CUSTOM_DATE',
        'adUnitView': 'FLAT',
        'dimensionAttributes': ['LINE_ITEM_COST_PER_UNIT', 'LINE_ITEM_COST_TYPE', 'LINE_ITEM_START_DATE_TIME', 'LINE_ITEM_END_DATE_TIME',
                                'LINE_ITEM_LIFETIME_IMPRESSIONS'],
        'startDate': {'year': '2012', 'month': '6', 'day': '1'},
        'endDate': {'year': '2012', 'month': '6', 'day': '3'}
    }
}

query = report_job['reportQuery']
timer = 1;

# Run report.
report_job = report_service.RunReportJob(report_job)[0]

# Wait for report to complete.
status = report_job['reportJobStatus']
while status != 'COMPLETED' and status != 'FAILED':
  print 'Report job with \'%s\' id is still running.' % report_job['id']
  time.sleep(30)
  timer += 1
  status = report_service.GetReportJob(report_job['id'])[0]['reportJobStatus']

if status == 'FAILED':
  print ('Report job with id \'%s\' failed to complete successfully.'
         % report_job['id'])
else:
  print 'Report job with id \'%s\' completed successfully.' % report_job['id']

# Change to your preffered export format.
export_format = 'XLSX'

# Download report data.
data = DfpUtils.DownloadReport(report_job['id'], export_format, report_service)
print 'Report downloaded'

# Write to  file
f = open('dfp_report_' + report_job['id'] + '.csv','w')
f.write(data)
f.close()

minutes = timer / 2
print 'Report completed in ' + str(minutes) + ' minutes'
  
log = open('success.log','a')
m = 'Report id %s downladed in %s minutes, %s\n' % (report_job['id'],minutes,query)
log.write(m)
log.close()